<template>
  <VTable ref="tableRef" v-bind="tableOptins">
    <template #form="{ form }">
      <el-cascader
        :options="optionsData?.menusList || []"
        v-model="form.menu_id"
        :props="propsCascader"
        clearable
        placeholder="菜单"
        style="width: 300px"
      />
      <el-input
        v-model="form.name"
        style="width: 300px"
        placeholder="字段名称"
        clearable
        prefix-icon="Search"
      ></el-input>
      <el-select
        v-model="form.status"
        clearable
        style="width: 90px"
        placeholder="状态"
      >
        <el-option
          v-for="item in optionsData?.status || []"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </template>
    <template #toolbar_btns>
      <el-button
        type="primary"
        icon="Plus"
        @click="handleAdd(null)"
        v-hasPermi="[userSysAuthList.attribute.add_field_attribute]"
        >新增</el-button
      >
      <el-button
        @click="batchOptionsRole({ label: '批量分配角色', value: '5' })"
        v-hasPermi="[userSysAuthList.attribute.manage_field_attribute_roles]"
        >批量分配角色</el-button
      >
      <el-button
        @click="batchOptionsUser({ label: '批量分配人员', value: '6' })"
        v-hasPermi="[userSysAuthList.attribute.manage_field_attribute_people]"
        >批量分配人员</el-button
      >
    </template>
  </VTable>
  <VLog ref="roleLog" :api="api.fieldAttrOplog" options="field_attr_id"></VLog>
  <Add
    v-model="addVisible"
    :id="addId"
    @refresh="refresh"
    @close="addId = null"
    :options="optionsData"
  />
  <VRoleManage
    v-model="roleVisible"
    :data="roleData"
    :api="roleApi"
    @close="roleData = {}"
    @refresh="refresh"
  ></VRoleManage>
  <VUserManage
    v-model="userVisible"
    :data="userData"
    :api="userApi"
    @close="userData = {}"
    @refresh="refresh"
  ></VUserManage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { propsCascader } from "../../data.js";
import VLog from "@/components/VLog";
import api from "../../api/index.js";
import Add from "../add/index";
import VRoleManage from "@/components/VRoleManage";
import VUserManage from "@/components/VUserManage";
import { userSysAuthList } from "@/Auth/userSys.js";
import { isPermission } from "@/hooks/permission.js";
const props = defineProps({
  optionsData: { type: Object, default: () => {} },
});
const { optionsData } = toRefs(props);
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {},
  },
  columns: [
    { type: "checkbox", width: "40" },
    {
      field: "name",
      title: "字段名称",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-link type="primary" underline={false}>
                {row.name}
              </el-link>
            </div>
          );
        },
      },
    },
    { field: "value", title: "字段值" },
    { field: "menu_id_text", title: "所属模块" },
    {
      field: "status",
      title: "状态",
      width: "150",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div onClick={() => handleSwitch(row)} class="inline-block">
                <el-switch
                  v-model={row.status}
                  active-value={1}
                  inactive-value={0}
                ></el-switch>
              </div>
            </div>
          );
        },
      },
    },
    { field: "create_user_text", title: "添加人", width: "150" },
    {
      title: "操作",
      fixed: "right",
      width: "300",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {isPermission([
                userSysAuthList.attribute.edit_field_attribute,
              ]) && (
                <el-button
                  type="primary"
                  link
                  onClick={() => handleAdd(row.id)}
                >
                  编辑
                </el-button>
              )}
              {isPermission([
                userSysAuthList.attribute.manage_field_attribute_roles,
              ]) && (
                <el-button
                  type="primary"
                  onClick={() => {
                    handleRoleManage(row);
                  }}
                  link
                >
                  分配角色
                </el-button>
              )}
              {isPermission([
                userSysAuthList.attribute.manage_field_attribute_people,
              ]) && (
                <el-button
                  type="primary"
                  onClick={() => {
                    handleUesrManage(row);
                  }}
                  link
                >
                  分配人员
                </el-button>
              )}
              <el-button type="primary" onClick={() => handleLog(row.id)} link>
                日志
              </el-button>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page, form }) => {
        return api.fieldAttrList({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});

const handleSwitch = async (val) => {
  const { code, message } = await api.fieldAttrStatus({ id: val.id });
  if (code != 200) return ElMessage.error(message);
  ElMessage.success("更新成功!");
};
const roleLog = ref();
const handleLog = (id) => {
  roleLog.value.open(id);
};
const addVisible = ref(false);
const addId = ref("");
const handleAdd = (val) => {
  addId.value = val;
  addVisible.value = true;
};

const roleData = ref({});
const roleVisible = ref(false);
const roleApi = ref("");
const batchOptionsRole = () => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id);
  roleData.value = {
    roletitle: "",
    roleType: "字段",
    roleData: [],
    parmas: { field_attr_ids: ids },
  };
  roleApi.value = api.fieldBatchRccessRole;
  roleVisible.value = true;
};
const handleRoleManage = async (val) => {
  const { data } = await api.getfieldAttrAccessRole({ field_attr_id: val.id });
  roleData.value = {
    roletitle: val.name,
    roleType: "字段",
    roleData: data?.role_ids || [],
    parmas: { field_attr_id: val.id },
  };
  roleApi.value = api.setfieldAttrAccessRole;
  roleVisible.value = true;
};

const userData = ref({});
const userVisible = ref(false);
const userApi = ref("");
const batchOptionsUser = () => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id);
  userData.value = {
    userData: [],
    parmas: { field_attr_ids: ids },
  };
  userApi.value = api.fieldBatchRccessUser;
  userVisible.value = true;
};
const handleUesrManage = async (val) => {
  const { data } = await api.getfieldAttrAccesUser({ field_attr_id: val.id });
  userData.value = {
    userData: data?.user_ids || [],
    parmas: { field_attr_id: val.id },
  };
  userApi.value = api.setfieldAttrAccesUser;
  userVisible.value = true;
};

const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
</script>
<style lang="scss" scoped>
.vx-table {
  height: calc(100% - 40px) !important;
}
</style>
